"""
按下ctrl+c
或
接受到sigint信号, 主动释放资源, 退出程序
"""

import signal
import rclpy
from rclpy.node import Node
from std_msgs.msg import String, Int32


class MinimalPublisher(Node):

    def __init__(self):
        super().__init__("trap_signal_int")
        self.pub = self.create_publisher(Int32, "trap_signal_int", 1)
        timer_period = 1  # seconds
        self.timer = self.create_timer(timer_period, self.timer_callback)
        self.i = 0
        self.log_init()
        # 配置信号处理函数
        signal.signal(signal.SIGINT, self.handler_signal)

    def __exit__(self):
        self.log_exit()

    def timer_callback(self):
        msg = Int32()
        msg.data = self.i
        self.pub.publish(msg)
        self.get_logger().info('Publishing: "%s"' % msg.data)
        self.fp.write(f"publish msg.data: {msg.data}\n")
        self.i += 1

    def log_init(self):
        self.fp = open("log.txt", "w")

    def log_exit(self):
        if self.fp:
            self.fp.flush()
            self.fp.close()
            self.fp = None
            print("主动释放文件资源, 退出程序")

    def handler_signal(self, signum, frame):
        print(f"handler signal {signum}")
        self.log_exit()
        print("主动释放资源, 退出程序")

        # 由于捕获signal信号,
        self.destroy_node()
        rclpy.shutdown()


def main(args=None):
    rclpy.init(args=args)
    ros_node = MinimalPublisher()
    rclpy.spin(ros_node)
    # ros_node.destroy_node()
    # rclpy.shutdown()
    print("程序正常退出")


if __name__ == "__main__":
    main()
